﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Devices.Sensors;


namespace TankIt
{
    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        Engine gameEngine;



        // A variety of rectangle colors
        Texture2D groundTexture;

        // For rendering the XAML onto a texture
        UIElementRenderer elementRenderer;


        SoundEffect soundEffect;

        Accelerometer accelerometer;


        UdpAnySourceMulticastChannel client;

        float turn;
        float forw;

        public GamePage()
        {
            InitializeComponent();
            
            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;
            
            
            gameEngine = new Engine(contentManager);

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            // Use the LayoutUpdate event to know when the page layout 
            // has completed so we can create the UIElementRenderer
            LayoutUpdated += new EventHandler(GamePage_LayoutUpdated);

            
        }


        void GamePage_LayoutUpdated(object sender, EventArgs e)
        {
            // Create the UIElementRenderer to draw the XAML page to a texture.

            // Check for 0 because when we navigate away the LayoutUpdate event
            // is raised but ActualWidth and ActualHeight will be 0 in that case.
            if (ActualWidth > 0 && ActualHeight > 0 && elementRenderer == null)
            {
                elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);
            
            // TODO: use this.content to load your game content here
            groundTexture = contentManager.Load<Texture2D>("terrain2");
            gameEngine.load();

            if (accelerometer == null)
            {
                // Instantiate the Accelerometer.
                accelerometer = new Accelerometer();
                accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
                accelerometer.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(accelerometer_CurrentValueChanged);
            }

            try
            {
                accelerometer.Start();
            }
            catch (InvalidOperationException ex)
            {
                
            }


            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
            
        }


        void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
        {
            // Call UpdateUI on the UI thread and pass the AccelerometerReading.
            Dispatcher.BeginInvoke(() => UpdateUI(e.SensorReading));
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
         
         // Move the sprite around.

            
            gameEngine.update(e);


        }


        private void UpdateUI(AccelerometerReading accelerometerReading)
        {

            Vector3 acceleration = accelerometerReading.Acceleration;

            turn = acceleration.Y;
            forw = acceleration.Z;

                if (turn>0.3f)
                {
                    gameEngine.left=true;
                    gameEngine.right = false;
                }
                else if (turn < -0.3f)
                {
                    gameEngine.right = true;
                    gameEngine.left = false;
                }
                else{
                    gameEngine.right = false;
                    gameEngine.left = false;
                }
                
             
                if (forw > 0.2f){
                        gameEngine.back = true;
                        gameEngine.frente = false;
                    }
                else if (forw < -0.2f){
                        gameEngine.frente=true;
                        gameEngine.back = false;
                }
                else{      
                    gameEngine.back = false;
                    gameEngine.frente = false;
                } 
            
        }


        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);

            // Render the Silverlight controls using the UIElementRenderer
            elementRenderer.Render();
            // Draw the sprite
            spriteBatch.Begin();

            //desenha o terreno
            spriteBatch.Draw(groundTexture, Vector2.Zero, Color.White);
            

            gameEngine.draw(spriteBatch);
            // TODO: Add your drawing code here
            
            // Draw the rectangle in its new position
           // spriteBatch.Draw(texture, spritePosition, Color.White);
            
     

            // Using the texture from the UIElementRenderer, 
            // draw the Silverlight controls to the screen
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);

            spriteBatch.End();

        }

        private void ColorPanelToggleButton_Click(object sender, RoutedEventArgs e)
        {
            gameEngine.dispara('p');
        }
    }
}